package com.algorithm.ch1.cjm2.array;


import com.sun.tools.javac.util.Assert;

/**
 * Created by jieming.chen on 2019-07-16
 */
public class MaxProfit {

    public static void main(String[] args) {
        int[] nums = {7,1,5,3,6,4};
        int[] nums1 = {1,2,3,4,5};
        int[] nums2 = {7,6,4,3,1};

        Assert.check(maxProfit(nums) == 7);
        Assert.check(maxProfit(nums1) == 4);
        Assert.check(maxProfit(nums2) == 0);
    }

    private static int maxProfit(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int result = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            // 买，上升趋势
            int bug = nums[i];
            while (i < nums.length -1 && nums[i] > nums[i+1]) {
                bug = nums[++i];
            }
            // 卖，下降趋势
            int sell = nums[i];
            while (i < nums.length -1 && nums[i] < nums[i+1]) {
                sell = nums[++i];
            }
            result += sell - bug;
        }
        return result;
    }

    /**
     * 分析上升趋势即可
     *
     * @param nums
     * @return
     */
    private static int maxProfit1(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int result = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[i - 1]) {
                result += nums[i] - nums[i - 1];
            }
        }
        return result;
    }


}
